package com.yaxin.outsourcing.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.util.Matrix;
import org.apache.pdfbox.multipdf.LayerUtility;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;

import java.util.List;

public class CardSheetUtil {

    private static final float A4_WIDTH = PDRectangle.A4.getWidth();
    private static final float A4_HEIGHT = PDRectangle.A4.getHeight();

    private static final float CARD_WIDTH = 9.0f * 28.35f;   // 255pt
    private static final float CARD_HEIGHT = 5.5f * 28.35f;  // 156pt

    private static final int ROWS = 4;
    private static final int COLS = 2;
    private static final int CARDS_PER_PAGE = ROWS * COLS;

    // 增大边距和间隙
    private static final float MARGIN_X =30f;   // 增大左右边距
    private static final float MARGIN_Y = 50f;   // 增大上下边距
    private static final float GAP_X = 30f;      // 增大水平间隙
    private static final float GAP_Y = 25f;      // 增大垂直间隙


    public static PDDocument generateCardSheets(List<PDDocument> cardDocs) throws Exception {
        PDDocument sheetDoc = new PDDocument();

        int total = cardDocs.size();
        int pageCount = (int) Math.ceil(total / (double) CARDS_PER_PAGE);

        int index = 0;
        for (int p = 0; p < pageCount; p++) {
            PDPage page = new PDPage(PDRectangle.A4);
            sheetDoc.addPage(page);

            PDPageContentStream content = new PDPageContentStream(sheetDoc, page);

            for (int row = 0; row < ROWS; row++) {
                for (int col = 0; col < COLS; col++) {
                    if (index >= total) break;

                    PDDocument cardDoc = cardDocs.get(index);
                    // 添加空值检查
                    if (cardDoc == null) {
                        index++;
                        continue;
                    }

// 用 LayerUtility 把 cardDoc 的第0页转成 FormXObject
                    LayerUtility layerUtility = new LayerUtility(sheetDoc);
                    PDFormXObject cardForm = layerUtility.importPageAsForm(cardDoc, 0);

// 画到指定位置
                    float x = MARGIN_X + col * (CARD_WIDTH + GAP_X);
                    float y = A4_HEIGHT - MARGIN_Y - (row + 1) * CARD_HEIGHT - row * GAP_Y;

                    content.saveGraphicsState();
                    content.transform(Matrix.getTranslateInstance(x, y));
                    content.drawForm(cardForm);
                    content.restoreGraphicsState();

                    index++;
                }
            }

            content.close();
        }

        return sheetDoc;
    }
}
